package com.ssb.plugins;

import com.apache.cache.util.Validator;
import com.apache.exception.BusinessException;
import com.apache.ius.plugin.CustomMethodPlugin;
import com.apache.ius.plugin.IusPluginUtil;
import com.apache.tools.DataMap;
import com.apache.tools.DateUtils;
import com.apache.tools.StrUtil;
import com.ssb.util.DateCalculationUtil;

import java.util.*;

/**
 * @Classname SelectOwnerPromotionFeePluginImpl
 * @Description 渠道商佣金管理列表查询
 * @Date 2020/4/15 18:42
 * @Created by fpc
 */
public class SelectFeeListPluginImpl implements CustomMethodPlugin {
    @Override
    public Object beforeInvoke(Map<String, Object> map) {
        String userType = String.valueOf(map.get("userType"));
        String userId = String.valueOf(map.get("ssCommissionDetail.w_userId"));
        String userEname = String.valueOf(map.get("ssCommissionDetail.wl_userEname"));
        String allUserIds="";
        List<DataMap> userList=null;
        if("broker".equals(userType)){//渠道商
            if(Validator.isEmpty(userId)){
                throw new BusinessException("参数【渠道商id】不能为空");
            }
            //获取所有子级渠道商
            userList = selectAllChildLevel(userId,userEname);

        }else if("manager".equals(userType)){
            userList=selectAllChannel(userEname);//查询所有的渠道商
        }else {
            throw new BusinessException("当前登录账号类型没有权限");
        }
        if("manager".equals(userType)&&StrUtil.isNull(userEname)){
            allUserIds="all";
        }else{
            if(userList!=null &&userList.size()>0){
                for (DataMap data:userList) {
                    String tempUserId = String.valueOf(data.get("userId"));
                    allUserIds+="'"+tempUserId+"',";
                }
                allUserIds = allUserIds.substring(0,allUserIds.length()-1);
            }else{
                throw new BusinessException("渠道商账户不存在");
            }
        }
        String startDate = StrUtil.doNull(String.valueOf(map.get("startDate")),"2020-02");
        String endDate = StrUtil.doNull(String.valueOf(map.get("endDate")), DateUtils.Now.fmt_yyyyMM());
        List<String> monthList = DateCalculationUtil.getMonthBetween(startDate, endDate);

        String cgsql = getCommissionGroupSql(startDate,endDate,allUserIds);
        List<DataMap> cgList = (List<DataMap>)IusPluginUtil.getInstance().select("ssb", cgsql, 0, 0);

        String casql = getCommissionApplySql(startDate,endDate,allUserIds);
        List<DataMap> caList = (List<DataMap>)IusPluginUtil.getInstance().select("ssb", casql, 0, 0);
        for (DataMap user:userList) {
            String user_id=String.valueOf(user.get("userId"));
            String user_ename=String.valueOf(user.get("userEname"));
            String user_cname=String.valueOf(user.get("userCname"));
            Map<String,String> caMap = new HashMap();
            for (DataMap dataMap:caList){
                if(user_id.equals(dataMap.get("applyUserId"))){
                    caMap.put(String.valueOf(dataMap.get("yearmonth")),String.valueOf(dataMap.get("money")));
                }
            }
            DataMap tempMap =null;
            String applyMoney=null;
            for (String month:monthList) {
                boolean flag = true;
                applyMoney = StrUtil.doNull(caMap.get(month),"0.00");
                group:
                for (DataMap data : cgList) {
                    if(user_id.equals(data.get("userId"))) {
                        if (data.get("yearmonth").equals(month)) {
                            flag = false;
                            data.put("applymoney", applyMoney);
                            break group;
                        }
                    }
                }
                if(flag){
                    tempMap = new DataMap();
                    tempMap.put("yearmonth",month);//结算周期
                    tempMap.put("num","0");//保单量
                    tempMap.put("amount","0.00");//应得推广费
                    tempMap.put("premium","0.00");//保费
                    tempMap.put("applymoney",applyMoney);//已提现推广费
                    tempMap.put("user_id",user_id);//渠道商id
                    tempMap.put("user_ename",user_ename);//渠道商账号
                    tempMap.put("user_cname",user_cname);//渠道商名称
                    cgList.add(tempMap);
                }
            }
        }

        Collections.sort(cgList, new Comparator<DataMap>() {
            @Override
            public int compare(DataMap o1, DataMap o2) {
                String yearmonth1 =  String.valueOf(o1.get("yearmonth"));
                String yearmonth2 =  String.valueOf(o2.get("yearmonth"));
                return yearmonth2.compareTo(yearmonth1);
            }
        });

        Map returnMap = new HashMap();
        returnMap.put(CustomMethodPlugin.pluginInnerReturn, cgList);
        returnMap.put(CustomMethodPlugin.resultMark, "T");
        return returnMap;
    }

    @Override
    public Object doInvoke(Map<String, Object> map) {
        return null;
    }

    @Override
    public Object afterInvoke(Map<String, Object> map) {
        return null;
    }
    private String getCommissionGroupSql(String startDate,String endDate,String allUserIds){
        String column = " DATE_FORMAT(scd.create_time, '%Y-%m') AS yearmonth, scd.user_id,scd.user_ename,scd.user_cname,COUNT(scd.info_id) AS num, cast(SUM(scd.amount) AS decimal(15,2)) AS amount, SUM(scd.premium) AS premium ";
        StringBuffer sb = new StringBuffer();
        sb.append("SELECT ");
        sb.append(column);
        sb.append("FROM ss_commission_detail scd WHERE 1=1 ");
        if(!"all".equals(allUserIds)){
            sb.append(" AND scd.user_id in("+allUserIds+")");
        }
        sb.append(" AND DATE_FORMAT(scd.create_time, '%Y-%m') >='"+startDate+"'");
        sb.append(" AND DATE_FORMAT(scd.create_time, '%Y-%m') <='"+endDate+"'");
        sb.append(" GROUP BY yearmonth,scd.user_id");
        return sb.toString();
    }

    private List<DataMap> selectAllChildLevel(String userId,String userEname) {
        StringBuffer sb = new StringBuffer();
        sb.append("SELECT user_id,user_cname,user_ename  FROM uct_user WHERE user_type='broker'");
        if(StrUtil.isNotNull(userEname)){
            sb.append(" AND user_ename like '%"+userEname+"%'");
        }
        sb.append(" AND FIND_IN_SET( user_id, queryChannelChildrenInfo ('");
        sb.append(userId);
        sb.append("'));");
        List<DataMap> cLlist = (List<DataMap>) IusPluginUtil.getInstance().select("plateform",sb.toString(), 0, 0);
        return cLlist;
    }
    private List<DataMap> selectAllChannel(String userEname) {
        StringBuffer sb = new StringBuffer();
        sb.append("SELECT user_id,user_cname,user_ename  FROM uct_user WHERE user_type='broker'");
        if(StrUtil.isNotNull(userEname)){
            sb.append(" AND user_ename like '%"+userEname+"%'");
        }
        List<DataMap> cLlist = (List<DataMap>) IusPluginUtil.getInstance().select("plateform",sb.toString(), 0, 0);
        return cLlist;
    }

    private String getCommissionApplySql(String startDate,String endDate,String allUserIds){
        String column = " DATE_FORMAT(sca.modify_time, '%Y-%m') AS yearmonth, SUM(sca.money) AS money,sca.apply_user_id ";
        StringBuffer sb = new StringBuffer();
        sb.append("SELECT ");
        sb.append(column);
        sb.append("FROM ss_cash_apply sca WHERE sca.apply_status='90' ");
        if(!"all".equals(allUserIds)){
            sb.append(" AND sca.apply_user_id in("+allUserIds+")");
        }
        sb.append(" AND DATE_FORMAT(sca.modify_time, '%Y-%m') >='"+startDate+"'");
        sb.append(" AND DATE_FORMAT(sca.modify_time, '%Y-%m') <='"+endDate+"'");
        sb.append("GROUP BY yearmonth,sca.apply_user_id");
        return sb.toString();
    }
}
